package com.jz.community.moduleauthorization.register.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.reflection.refreshtoken.RefreshTokenActionReflectUtils;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.GetBindWeChatInfoTask;
import com.jz.community.basecomm.task.GetCouponModeTask;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.CommUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.commview.view.widget.LoginButton;
import com.jz.community.moduleauthorization.R;
import com.jz.community.moduleauthorization.R2;
import com.jz.community.basecomm.bean.LoginInfo;
import com.jz.community.moduleauthorization.login.bean.LoginType;
import com.jz.community.moduleauthorization.login.task.AddShopEarningsTask;
import com.jz.community.moduleauthorization.register.bean.RegisterInfo;
import com.jz.community.moduleauthorization.register.constant.RegisterConstant;
import com.jz.community.moduleauthorization.register.presenter.RegisterPresenter;
import com.jz.community.moduleauthorization.utils.LoginEmptyUtils;
import com.jz.community.moduleauthorization.utils.SmsCodeConstant;
import com.jz.community.basecomm.utils.TimeUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by Tony.Fan on 2018/3/20 15:20
 * <p>
 * 注册
 */
@Route(path = RouterIntentConstant.MODULE_AUTHORIZATION_REGISTER)
public class RegisterActivity extends BaseMvpActivity<RegisterView.View, RegisterPresenter> implements RegisterView.View {
    @BindView(R2.id.register_phone_et)
    EditText registerPhoneEt;
    @BindView(R2.id.register_code_tv)
    TextView registerCodeTv;
    @BindView(R2.id.register_code_et)
    EditText registerCodeEt;
    @BindView(R2.id.register_pwd_et)
    EditText registerPwdEt;
    @BindView(R2.id.register_pwd_checkbox)
    CheckBox registerPwdCheckbox;
    @BindView(R2.id.register_pwd_again_et)
    EditText registerPwdAgainEt;
    @BindView(R2.id.register_confirm_pwd_checkbox)
    CheckBox registerConfirmPwdCheckbox;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.title_right)
    TextView titleRight;
    @BindView(R2.id.register_btn)
    LoginButton registerBtn;
    private String registrationID;
    private TimeUtils timeUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        setImmersionBar(titleToolbar);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_register_layout;
    }

    @Override
    protected void initDatas() {
        registrationID = JPushInterface.getRegistrationID(this);
        setOnCheckedChangeListener();
        initTitle("注册", "登录");
        registerBtn.setText("注册");
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN);
                finish();
            }
        });
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerBtnClick(v);
            }
        });
    }

    private void setOnCheckedChangeListener() {
        registerPwdCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // TODO Auto-generated method stub
            if (isChecked) {
                //如果选中，显示密码
                registerPwdEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                registerPwdCheckbox.setBackgroundResource(R.mipmap.ic_open_eyes);
            } else {
                //否则隐藏密码
                registerPwdEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                registerPwdCheckbox.setBackgroundResource(R.mipmap.ic_close_eyes);
            }
        });
        registerConfirmPwdCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // TODO Auto-generated method stub
            if (isChecked) {
                //如果选中，显示密码
                registerPwdAgainEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                registerConfirmPwdCheckbox.setBackgroundResource(R.mipmap.ic_open_eyes);
            } else {
                //否则隐藏密码
                registerPwdAgainEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                registerConfirmPwdCheckbox.setBackgroundResource(R.mipmap.ic_close_eyes);
            }
        });
    }

    //注册
    public void registerBtnClick(View view) {
        CommUtils.hideKeyboard(view, this);
        String tel = registerPhoneEt.getText().toString().trim();
        String code = registerCodeEt.getText().toString().trim();
        String password = registerPwdEt.getText().toString().trim();
        String password_again = registerPwdAgainEt.getText().toString().trim();
        if (LoginEmptyUtils.isHasRegisterEmpty(this, tel, code, password, password_again)) {
            LoggerUtils.fLog().i("json传值" + JSON.toJSONString(mapParam(tel, password, code)));
            mPresenter.getRegisterInfo(mapParam(tel, password, code));
        }
    }

    /**
     * 注册用户信息
     *
     * @param phone
     * @return
     */
    private HashMap<String, String> mapParam(String phone, String password, String vcode) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userName", phone);
        map.put("passWord", password);
        map.put("comeFrom", AppConstants.APPID);
        map.put("userType", RegisterConstant.USERTYPE);
        map.put("roleIds", RegisterConstant.ROLEID);
        map.put("phone", phone);
        map.put("vcode", vcode);
        return map;
    }

    //获取验证码
    public void loginObtainCodeBtnClick(View view) {
        String loginPhone = registerPhoneEt.getText().toString().trim();
        if (LoginEmptyUtils.isLoginPhone(this, loginPhone)) {
            mPresenter.getLoginSmsCode(loginPhone, SmsCodeConstant.SMS_TYPE_USER_REGISTER);
        }
    }

    /**
     * 验证码结果处理状态
     *
     * @param loginInfo
     */
    private void handelSmsCodeState(LoginInfo loginInfo) {
        if (!Preconditions.isNullOrEmpty(loginInfo.getVcode())) {
            if (timeUtils == null) {
                WpToast.l(this, "验证码发送成功");
                timeUtils = new TimeUtils(120 * 1000, 1000, RegisterActivity.this, registerCodeTv);
            }
            timeUtils.start();
        } else {
            WpToast.l(this, loginInfo.getMessage());
            refreshRegainBackground();
        }
    }

    @Override
    protected RegisterPresenter createPresenter() {
        return new RegisterPresenter(this);
    }

    @Override
    public void showLoginInfo(LoginInfo loginInfo) {
        if (!Preconditions.isNullOrEmpty(loginInfo.getAccess_token())) {
            saveUserMsg(loginInfo);
            WpToast.l(this, "登录成功");
            handleCouponModel();
            addShopEarningsData();
            sendToLoginState(true);
        } else {
            WpToast.l(this, loginInfo.getMessage());
        }
    }

    /**
     * 新用户注册发放优惠券
     */
    private void handleCouponModel() {
        new GetCouponModeTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {

            }
        }).execute("3");
    }

    /**
     * 保存用户基本信息
     *
     * @param loginInfo
     */
    private void saveUserMsg(LoginInfo loginInfo) {
        BaseSpUtils.getInstance().setAccessToken(RegisterActivity.this, loginInfo.getAccess_token());
        BaseSpUtils.getInstance().setRefreshToken(RegisterActivity.this, loginInfo.getRefresh_token());
        if (!Preconditions.isNullOrEmpty(loginInfo.getProfile())) {
            BaseSpUtils.getInstance().setUserId(RegisterActivity.this, loginInfo.getProfile().getAttributes().getUser_id());
        }
    }

    //发送登录状态
    private void sendToLoginState(boolean isLogin) {
        bindJupshID();
        saveLoginState(1, isLogin);
    }

    /**
     * 保存登录状态
     *
     * @param loginType
     */
    private void saveLoginState(int loginType, boolean isLogin) {
        BaseSpUtils.getInstance().setLoginType(this, loginType);
        BaseSpUtils.getInstance().setIsLogin(this, true);
        ToLoginEvent toLoginEvent = new ToLoginEvent();
        toLoginEvent.setToPwdLogin(isLogin);
        RxBus.getInstance().post(toLoginEvent);
        finish();
    }

    /**
     * 绑定推送ID
     */
    private void bindJupshID() {
        RefreshTokenActionReflectUtils.jumpBindJupshPage(this, JPushInterface.getRegistrationID(this));
    }

    /**
     * 添加收益商家端
     */
    private void addShopEarningsData() {
        new AddShopEarningsTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {

            }
        }).execute(registerPhoneEt.getText().toString().trim());
    }

    @Override
    public void showSmsCodeInfo(LoginInfo loginInfo) {
        handelSmsCodeState(loginInfo);
    }

    @Override
    public void showRegisterInfo(RegisterInfo registerInfo) {
        if (!Preconditions.isNullOrEmpty(registerInfo)) {
            WpToast.l(this, "注册成功");
            bindWeChat(registerPhoneEt.getText().toString().trim(), "", "2");
            registerBtn.setEnabled(false);
            loginByPassword();
        } else {
            if (!Preconditions.isNullOrEmpty(registerInfo.getMessage())) {
                WpToast.l(this, registerInfo.getMessage());
                refreshRegainBackground();
            }
        }
    }

    /**
     * 绑定数据同步
     *
     * @param openId
     * @param unionId
     * @param type
     */
    private void bindWeChat(String openId, String unionId, String type) {
        new GetBindWeChatInfoTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
            }
        }).execute(openId, unionId, type);
    }

    @Override
    public void showError() {
        refreshRegainBackground();
    }

    //登录
    private void loginByPassword() {
        String loginName = registerPhoneEt.getText().toString().trim();
        String loginPwd = registerPwdEt.getText().toString().trim();
        mPresenter.getLoginInfo(loginName, loginPwd, LoginType.DEFUALT.getTag(), "", CommUtils.getDeviceID(this), registrationID);
    }

    @Override
    public Context getContext() {
        return this;
    }

    /**
     * 刷新按钮
     */
    private void refreshRegainBackground() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                registerBtn.regainBackground("注册");
            }
        }, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeUtils != null) {
            timeUtils.cancel();
        }
    }
}
